package kassiopeia.agent.plugin;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import kassiopeia.agent.AgentIDHolder;
import kassiopeia.agent.alerting.PluginAlerting;
import kassiopeia.agent.infrastructure.AliveAgentsHolder;
import kassiopeia.agent.infrastructure.EventRouter;
import kassiopeia.commons.model.plugin.Output;
import kassiopeia.commons.model.plugin.Parameter;
import kassiopeia.commons.model.plugin.PluginDescriptor;
import kassiopeia.plugin.Context;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ContextFactory {

    //@Value("${plugin.temporary.directory}")
    private String rootTmpDir;

    @Autowired
    private AliveAgentsHolder agentsHolder;

    @Autowired
    private EventRouter eventRouter;

    @Autowired
    private PluginAlerting pluginAlerting;

    public Context newInstance(PluginDescriptor descriptor, ClassLoader loader, String instanceId) {
        ContextImpl context = new ContextImpl();

        context.setInstanceId(instanceId);
        context.setAgentId(AgentIDHolder.getThisAgentId());
        //context.setMessageSender(messageSender);
        context.setAlerting(pluginAlerting);
        context.setAliveAgentsHolder(agentsHolder);
        context.setPluginTemporaryDirectory(createPluginTmpDir(instanceId));
        context.setParameters(prepareParameters(descriptor));
        context.setOutputsIds(prepareOutputsIds(descriptor));
        context.setClassLoader(loader);
        context.setEventRouter(eventRouter);

        return context;
    }

      private List<String> prepareOutputsIds(PluginDescriptor descriptor) {
        List<String> outputsIdsTmp = new ArrayList<String>();

        List<Output> outputs = descriptor.getOutputDescriptors();

        if(outputs != null) {
            for(Output output : outputs) {
                outputsIdsTmp.add(output.getId());
            }
        }

        return outputsIdsTmp;
    }

    private File createPluginTmpDir(String instanceId) {
        File tmpPluginDir = new File(rootTmpDir, instanceId);
        tmpPluginDir.deleteOnExit();
        return tmpPluginDir;
    }

      private Map<String, String> prepareParameters(PluginDescriptor descriptor) {
          Map<String, String> parametersTmp = new HashMap<String, String>();
          if(descriptor.getConfiguration() != null) {
              for(Parameter parameter : descriptor.getConfiguration()) {
                  parametersTmp.put(parameter.getId(), parameter.getDefaultValue());
              }
          }

          return parametersTmp;
     }
}
